package com.wcity.manage.service.impl;

import com.wcity.manage.common.utils.Excel;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.Log;
import com.wcity.manage.common.utils.StringUtil;
import com.wcity.manage.dao.mapper.BlockMapper;
import com.wcity.manage.dao.mapper.ModuleManageMapper;
import com.wcity.manage.dao.mapper.RegisterMapper;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.ModuleManage;
import com.wcity.manage.dao.model.Register;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.service.AuthService;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.CommentService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by jn on 2016/12/12.
 *
 */
@Service
public class BlockServiceImpl implements BlockService {

    @Override
    public Object findBlockList(String area, String blockName, String registerId) {

        Block b = new Block();
        if ( !"杭州".equals( area ) ) b.setBlockArea( area );
        b.setBlockName( blockName );

        //获取上线所有用户
        List<Integer> userIds = new ArrayList<>();
        if ( StringUtil.isNumeric( registerId ) ) {

            Register register = registerMapper.find( Integer.parseInt( registerId ) );
            if ( register != null ) userIds.add( register.getUserId() );

        } else {
            userIds = manageMapper.findOnlineUser();
        }

        if ( userIds == null || userIds.size() <= 0 ) return "暂无小区入驻";

        List<Block> list = blockMapper.findByBlock( b, userIds );

        List<Object> result = new ArrayList<>();
        for ( Block block : list ) {

            Map<String,Object> map = new HashMap<>();
            map.put("blockId",block.getId());
            map.put("blockName",block.getBlockName());
            map.put("workNo",block.getUser().getWorkNo());
            map.put("blockAddr",block.getBlockAddr());
            result.add( map );

        }

        return result;
    }

    @Override
    public Object blockRegisterIn(String blockId, String registerId,String token) {

        Block block = blockMapper.find( Integer.parseInt( blockId ) );

        if ( block == null ) return "小区不存在";
        // 判断物业社区状态
        ModuleManage manage = manageMapper.findByUserId( block.getUserId() );
        if ( manage.getStatus() != 1 ) return "该小区尚未入住";

        if ( !StringUtil.isBlank( registerId ) ) {

            // token验证
            String errorMsg = authService.checkToken( token, registerId );
            // 注册后第一次选择小区
            String result = "未入住任何小区";
            if ( !StringUtil.isBlank( errorMsg ) && !result.equals( errorMsg ) ) return errorMsg;

            Register r = registerMapper.find( Integer.parseInt( registerId ) );
            // 只能入住最初选择的那个社区
            if ( r.getUserId() > 0 && r.getUserId() != block.getUserId() ) return "该用户已经入住其他社区";

            Register register = new Register();
            register.setId( Integer.parseInt( registerId ) );
            register.setBlockId( Integer.parseInt( blockId ) );
            register.setUserId( block.getUserId() );

            registerMapper.update( register );
        }

        Map<String,Object> map = JSONUtil.getSuccessJson();
        map.put("userId",block.getUser().getId());
        map.put("workNo",block.getUser().getWorkNo());

        return map;
    }

    @Override
    public String blockAdd(Block block, User user) {

        Block b = new Block();
        b.setUserId( user.getId() );
        b.setBlockName( block.getBlockName() );
        if ( blockMapper.findList( b ).size() > 0 ) return "该小区已经存在";

        block.setUserId( user.getId() );

        String img = block.getBlockImge();

        if ( !StringUtil.isBlank( img ) ) block.setBlockImge( StringUtil.digestStr( img ) );

        try {
            if ( blockMapper.insert( block ) <= 0 ) return "新增失败";
        } catch (DataAccessException e) {
            Log.error( "blockAdd error, {}", e.getMessage(), e );
            return "服务器异常";
        }

        return "";
    }

    @Override
    public String blockEdit(Block block) {

        String img = block.getBlockImge();

        if ( !StringUtil.isBlank( img ) ) block.setBlockImge( StringUtil.digestStr( img ) );

        try {
            if ( blockMapper.update( block ) <= 0 ) return "修改失败";
        } catch (DataAccessException e) {
            Log.error( "blockEdit error, {}", e.getMessage(), e );
            return "服务器异常";
        }

        return "";
    }

    @Override
    public String blockDel(int blockId) {

        int count = registerMapper.countByBlock( blockId );

        Block block = blockMapper.find( blockId );

        if ( count > 0 ) return "该小区下有用户入住，删除失败";

        if ( block == null ) return "小区不存在，删除失败";

        blockMapper.delete( blockId );
        //删除oss图片
        commentService.delPic( block.getBlockImge() );

        return "";
    }

    @Override
    public void blockExport(Block block, OutputStream outputStream) {

        List<Block> blockList = blockMapper.findList( block );
        Excel<Block> excel = new Excel<>();

        String[] headersArray = {"小区名称","地址","区县","小区管理员","联系电话","小区热线","创建时间"};
        // 列标题list
        List<String> headers = Arrays.asList( headersArray );

        String[] propertyArray = {"blockName","blockAddr","blockArea","blockManager","blockTel","telephone","createTime"};
        // 需要导出的属性list
        List<String> propertyList = Arrays.asList( propertyArray );

        excel.exportExcel( blockList, headers, propertyList, "小区列表", outputStream, true );

    }

    @Override
    public String blockImport(CommonsMultipartFile file, User user) {

        if ( file == null || file.getSize() <= 0 ) return "请选择文件";

        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            Log.error( "blockImport error, {}", e.getMessage(), e );
            return "上传文件失败";
        }

        String originName = file.getOriginalFilename();
        Workbook workbook;
        if ( originName.endsWith( "xlsx" ) ) {
            try {
                workbook = new XSSFWorkbook( inputStream );
            } catch (IOException e) {
                Log.error( "blockImport error, {}", e.getMessage(), e );
                return "文件解析失败";
            }
        } else {
            return "文件格式不正确，请下载模板";
        }

        String[] areas = {"杭州","滨江","西湖","上城","下城","拱墅","江干","萧山","余杭","富阳"};
        List<String> areaList = Arrays.asList( areas );

        List<String> blockNames = blockMapper.findBlockName( user.getId() );

        List<Block> blockList = new ArrayList<>();
        Sheet sheet = workbook.getSheetAt( 0 );
        int index = 0;
        for ( Row row : sheet ) {

            if ( index == 0 ) {
                index++;
                continue;
            }

            String blockName = row.getCell( 0 ).getStringCellValue();
            String blockAddr = row.getCell( 1 ).getStringCellValue();
            String blockArea = row.getCell( 2 ).getStringCellValue();
            String blockManger = row.getCell( 3 ).getStringCellValue();
            String blockTel = row.getCell( 4 ).getStringCellValue();
            String telephone = row.getCell( 5 ).getStringCellValue();

            if ( StringUtil.isBlank( blockName ) || blockName.length() > 50 ) return "小区名为空或者超过50个字符";
            if ( !StringUtil.isBlank( blockAddr ) && blockAddr.length() > 50 ) return "地址名超过50个字符";
            if ( !areaList.contains( blockArea ) ) return "区县名称错误，请从杭州八区中选择";
            if ( !StringUtil.isBlank( blockManger ) && blockManger.length() > 10 ) return "联系人超过10个字符";
            if ( !StringUtil.isBlank( blockTel ) && !StringUtil.isNumeric( blockTel, 11 ) ) return "联系电话不是11位数字";
            if ( !StringUtil.isBlank( telephone ) && telephone.length() > 20 ) return "小区热线超过20个字符";

            if ( blockNames.contains( blockName ) ) return blockName + "小区已存在，请删除后再导入";

            Block block = new Block();
            block.setUserId( user.getId() );
            block.setBlockName( blockName );
            block.setBlockAddr( blockAddr );
            block.setBlockArea( blockArea );
            block.setBlockManager( blockManger );
            block.setBlockTel( blockTel );
            block.setTelephone( telephone );
            block.setCreateTime( new Date() );

            blockList.add( block );

        }

        if ( blockList.size() <= 0 ) return "导入失败，数据为空";

        blockMapper.insertList( blockList );

        return null;
    }

    @Override
    public String blockImportTest(CommonsMultipartFile file, User user) {

        String[] propertyArray = {"blockName","blockAddr","blockArea","blockManager","blockTel","telephone"};
        // 需要导出的属性list
        List<String> propertyList = Arrays.asList( propertyArray );

        Excel<Block> excel = new Excel<>();
        try {

            Object result = excel.importExcel( file, propertyList, "com.wcity.manage.dao.model.Block" );

            if ( result instanceof String ) return (String) result;

            List<Block> blockList = (List<Block>) result;

            String[] areas = {"杭州","滨江","西湖","上城","下城","拱墅","江干","萧山","余杭","富阳"};
            List<String> areaList = Arrays.asList( areas );

            List<String> blockNames = blockMapper.findBlockName( user.getId() );

            for ( Block block : blockList ) {

                String blockName = block.getBlockName();
                String blockAddr = block.getBlockAddr();
                String blockArea = block.getBlockArea();
                String blockManger = block.getBlockManager();
                String blockTel = block.getBlockTel();
                String telephone = block.getTelephone();

                if ( StringUtil.isBlank( blockName ) || blockName.length() > 50 ) return "小区名为空或者超过50个字符";
                if ( !StringUtil.isBlank( blockAddr ) && blockAddr.length() > 50 ) return "地址名超过50个字符";
                if ( !areaList.contains( blockArea ) ) return "区县名称错误，请从杭州八区中选择";
                if ( !StringUtil.isBlank( blockManger ) && blockManger.length() > 10 ) return "联系人超过10个字符";
                if ( !StringUtil.isBlank( blockTel ) && !StringUtil.isNumeric( blockTel, 11 ) ) return "联系电话不是11位数字";
                if ( !StringUtil.isBlank( telephone ) && telephone.length() > 20 ) return "小区热线超过20个字符";

                if ( blockNames.contains( blockName ) ) return blockName + "小区已存在，请删除后再导入";

                block.setUserId( user.getId() );
                block.setCreateTime( new Date() );
            }

            blockMapper.insertList( blockList );

        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败";
        }

        return null;
    }

    @Override
    public Object getBlockImageList(String blockId) {

        Block block = blockMapper.find( Integer.parseInt( blockId ) );

        if ( block == null ) return "小区不存在";

        return commentService.imageList( block.getBlockImge() );
    }

    /**
     * 获取到小区信息
     * @param blockId
     * @return
     */
    public Block getBlockById( Integer blockId ){

        return blockMapper.getBlockById( blockId );
    }
    /**
     * 社区管理员管理的小区列表
     * @param queryMap
     * @return
     */
    @Override
    public List<Block> getAdminHaveBlockList( Map<String,Object> queryMap ){

        return blockMapper.blockList( queryMap );
    }

    @Resource private BlockMapper blockMapper;
    @Resource private RegisterMapper registerMapper;
    @Resource private CommentService commentService;
    @Resource private ModuleManageMapper manageMapper;
    @Resource private AuthService authService;

}
